// StudentExamDetailServlet.java
package student;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.Map;

@WebServlet("/StudentExamDetailServlet")
public class StudentExamDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取exam_id参数并验证
        String examIdParam = request.getParameter("exam_id");

        // 如果请求参数中没有exam_id，尝试从session中获取
        if (examIdParam == null || examIdParam.trim().isEmpty()) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                examIdParam = (String) session.getAttribute("currentExamId");
            }
        }

        // 检查参数是否为空
        if (examIdParam == null || examIdParam.trim().isEmpty()) {
            sendErrorResponse(response, "缺少考试ID参数");
            return;
        }

        int examId;
        try {
            examId = Integer.parseInt(examIdParam);
        } catch (NumberFormatException e) {
            sendErrorResponse(response, "无效的考试ID格式");
            return;
        }

        HttpSession session = request.getSession();
        Integer studentId = (Integer) session.getAttribute("student_id");

        if (studentId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        response.setContentType("application/json;charset=UTF-8");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        try {
            Connectmysql conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root", "root", "com.mysql.cj.jdbc.Driver");

            if (conn.open()) {
                // 验证学生权限
                String verifySql = "SELECT ec.class_id " +
                        "FROM exam_class ec " +
                        "JOIN student s ON ec.class_id = s.class_id " +
                        "WHERE ec.exam_id = ? AND s.student_id = ?";
                ResultSet verifyRs = conn.executeSql(verifySql, new Object[]{examId, studentId});

                if (!verifyRs.next()) {
                    sendErrorResponse(response, "您没有权限查看此考试");
                    return;
                }

                // 获取考试详情
                String sql = "SELECT e.exam_name, c.course_name, e.start_time, " +
                        "e.duration, e.status, e.total_score " +
                        "FROM exam e " +
                        "JOIN course c ON e.course_id = c.course_id " +
                        "WHERE e.exam_id = ?";

                ResultSet rs = conn.executeSql(sql, new Object[]{examId});
                Map<String, Object> examDetails = new LinkedHashMap<>();

                if (rs.next()) {
                    examDetails.put("exam_name", escapeJson(rs.getString("exam_name")));
                    examDetails.put("course_name", escapeJson(rs.getString("course_name")));

                    // 格式化时间
                    Timestamp startTime = rs.getTimestamp("start_time");
                    examDetails.put("start_time", startTime != null ?
                            escapeJson(sdf.format(startTime)) : "N/A");

                    examDetails.put("duration", rs.getInt("duration"));
                    examDetails.put("status", rs.getInt("status"));
                    examDetails.put("total_score", rs.getDouble("total_score"));

                    // 将考试ID存入session作为后备
                    request.getSession().setAttribute("currentExamId", examIdParam);
                } else {
                    sendErrorResponse(response, "未找到考试信息");
                    return;
                }

                response.getWriter().print(mapToJson(examDetails));
            } else {
                sendErrorResponse(response, "数据库连接失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendErrorResponse(response, "加载考试详情失败: " + e.getMessage());
        }
    }

    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print("{\"error\": \"" + escapeJson(message) + "\"}");
    }

    private String mapToJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) {
                json.append(",");
            }
            first = false;

            json.append("\"")
                    .append(escapeJson(entry.getKey()))
                    .append("\":");

            Object value = entry.getValue();
            if (value == null) {
                json.append("null");
            } else if (value instanceof String) {
                json.append("\"")
                        .append(escapeJson((String) value))
                        .append("\"");
            } else {
                json.append(value);
            }
        }

        json.append("}");
        return json.toString();
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}